from pathlib import Path
import os
from requests import get
import zipfile
import subprocess
import sys
import re
import logging
import traceback

logging.basicConfig(
    filename="C:\\users\\netease\\huyu-operator-log.txt", level=logging.DEBUG)
logger = logging.getLogger()

cmd_str = " ".join(sys.argv[1:])
logger.info("cmd: {0}".format(cmd_str))

cmd_head = ["start", "cmd", "/k"]

def init():
    try:
        p_str = "C:\\users\\netease\\frp"
        path = Path(p_str)
        path.mkdir(parents=True, exist_ok=True)
    
        # Get the current working directory
        cwd = os.getcwd()
    
        # Print the current working directory
        logger.info("Current working directory: {0}".format(cwd))
    
        # Change the current working directory
        os.chdir(p_str)
    
        # Print the current working directory
        logger.info("Current working directory: {0}".format(os.getcwd()))
    
        frp_file_url = "http://app-s3.outer.fuxi.netease.com/kubevirt:kubevirt/huyu-operator/frpc.zip"
        frp_path = "frpc"
        frp_file = frp_path + ".zip"
    
        # download frp
        with open(frp_file, "wb") as file:
            resp = get(frp_file_url)
            file.write(resp.content)
    
        # unzip
        with zipfile.ZipFile(frp_file, "r") as zip_ref:
            zip_ref.extractall(frp_path)
    
        os.chdir(frp_path)
    
        in_file = r'frpc-config.ini'
    
        subprocess.Popen(["frpc.exe", "-c", in_file])
        subprocess.Popen(["start", "powershell"], shell=True)
    
        # change work path
        cmds = cmd_str.split(";")
        path = cmds[0]
        # mkdir if not exists
        if not os.path.exists(path):
            path = Path(path)
            path.mkdir(parents=True, exist_ok=True)
        os.chdir(path)
    
        cmds = cmds[1:]
        for i in range(len(cmds)):
            logger.info("cmd: {0}".format(cmds[i]))
            cmds[i] = cmds[i].strip()
            c = cmds[i].split()
            logger.info("cmd: {0}".format(c))
            for j in range(len(c)):
                if c[j] == "python":
                    c[j] = "C:\\Python38\\python.exe"
                    break
            c = " ".join(c)
            logger.info("cmd: {0}".format(c))
            c = cmd_head + [c]
            logger.info("cmd: {0}".format(c))
            subprocess.Popen(c, shell=True)
    except BaseException as e:
        logger.error(e)
        traceback.print_exc()

def replace_in_file(in_file, out_file, search_text, replace_text):
    try:
        # Opening our text file in read only
        # mode using the open() function
        with open(in_file, 'r') as file:
    
            # Reading the content of the file
            # using the read() function and storing
            # them in a new variable
            data = file.read()
    
            # Searching and replacing the text
            # using the replace() function
            # data = data.replace(search_text, replace_text)
            data = re.sub(search_text, replace_text, data, count=2)
    
        # Opening our text file in write only
        # mode to write the replaced content
        with open(out_file, 'w') as file:
    
            # Writing the replaced data in our
            # text file
            file.write(data)
    except BaseException as e:
        logger.error(e)
        traceback.print_exc()

if __name__ == "__main__":
    init()    